<template>
    <div class="noteView">
        <div class="noteContainer">
            <!-- 左侧笔记列表 -->
            <div class="noteList">
                <div class="toolbar">
                    <div class="left-tools">
                        <el-button type="primary" @click="createNote">
                            <el-icon><Plus /></el-icon>新建笔记
                        </el-button>
                        <!-- <el-input
                            v-model="searchText"
                            placeholder="搜索笔记"
                            prefix-icon="Search"
                            clearable
                            @input="searchFunction(searchText)"
                        /> -->
                    </div>
                </div>
                <NoteList 
                    ref="noteListRef"
                    :notes="filteredNotes"
                    :current-note-id="currentNote.noteId"
                    @select="handleNoteSelect"
                    @delete="confirmDelete"
                    @batch-delete="handleBatchDelete"
                />
            </div>
            
            <!-- 右侧编辑 -->
            <div class="noteContent">
                <NoteEditor
                    v-model="currentNote.noteContent"
                    :title="currentNote.noteTitle"
                    @save="() => saveNote(currentNote)"
                    @delete="() => confirmDelete(currentNote)"
                    @change="handleEditorChange"
                    @titleChange="handleTitleChange"
                />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, inject } from 'vue';
import { useNoteStore, Note } from '@/store/modules/note/noteStore';
import { ElMessage, ElMessageBox } from 'element-plus';
import NoteList from '@/components/note/NoteList.vue';
import NoteEditor from '@/components/note/NoteEditor.vue';
import { Plus } from '@element-plus/icons-vue';
// import { SignUtil } from '@/util/signin';
import { useRouter } from 'vue-router';

const noteStore = useNoteStore();
const router = useRouter();
// const searchText = ref('');
const currentNote = reactive<Note>({
    noteId: 0,
    userId: 0,
    noteTitle: '',
    noteContent: '',
    updateTime: new Date(),
    isPublic: '0',
    createTime: new Date(),
    createBy: '',
    updateBy: '',
});

const noteListRef = ref();
// const hasSelectedNotes = computed(() => {
//     return noteListRef.value?.getSelectedNotes().length > 0;
// });

// 初始化
onMounted(async () => {
    // const userId = SignUtil.getUserId();
    // if (!userId) {
    //     ElMessage.error('请先登录');
    //     router.push('/loginRegister');
    //     return;
    // }

    try {
        await noteStore.initializeStore();
        // 如果有笔记，选择第一个
        if (noteStore.notes && noteStore.notes.length > 0) {
            handleNoteSelect(noteStore.notes[0]);
        } else {
            // 如果没有笔记，重置当前笔记
            resetCurrentNote();
        }
    } catch (error) {
        console.error('Failed to initialize notes:', error);
        ElMessage.error('加载笔记失败');
    }
});

// 计算属性
const filteredNotes = computed(() => noteStore.filteredNotes);

// 方法
// const handleSearch = (value: string) => {
//     noteStore.setSearchQuery(value);
// };

const handleNoteSelect = (note: Note) => {
    if (!note) return;
    Object.assign(currentNote, {
        ...note,
        noteId: note.noteId,
        userId: note.userId,
        noteTitle: note.noteTitle || '新建笔记',
        noteContent: note.noteContent || '',
        updateTime: note.updateTime ? new Date(note.updateTime) : new Date(),
        createTime: note.createTime ? new Date(note.createTime) : new Date()
    });
};

const createNote = async () => {
    try {
        const newNote = await noteStore.createNote();
        handleNoteSelect(newNote);
        noteStore.initializeStore();
        ElMessage.success('创建成功');
    } catch (error) {
        ElMessage.error('创建失败：' + error.message);
    }
};

const saveNote = async (note: Note) => {
    try {
        if (note.noteId) {
            const updatedNote = await noteStore.updateNote(note.noteId, {
                noteTitle: note.noteTitle,
                noteContent: note.noteContent,
                isPublic: note.isPublic
            });
            noteStore.initializeStore();
            ElMessage.success('保存成功');
        }
    } catch (error) {
        ElMessage.error('保存失败：' + error.message);
    }
};

const confirmDelete = async (note: Note) => {
    if (!note.noteId) return;
    
    try {
        await ElMessageBox.confirm('确定要删除这个笔记吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        
        await noteStore.deleteNote(note.noteId);
        if (note.noteId === currentNote.noteId) {
            resetCurrentNote();
            if (noteStore.notes.length > 0) {
                handleNoteSelect(noteStore.notes[0]);
            }
        }
        ElMessage.success('删除成功');
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败：' + error.message);
        }
    }
};

// const handleTemplate = (templateId: string) => {
//     const template = noteStore.templates[templateId];
//     if (template) {
//         currentNote.noteTitle = template.title;
//         currentNote.noteContent = template.content;
//     }
// };

const handleEditorChange = (content: string) => {
    currentNote.noteContent = content;
};

const handleTitleChange = (title: string) => {
    currentNote.noteTitle = title;
};

// 批量删除处理
const handleBatchDelete = async (notes: Note[]) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${notes.length} 个笔记吗？`,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        const ids = notes.map(note => note.noteId);
        await noteStore.batchDeleteNotes(ids);
        
        if (notes.some(note => note.noteId === currentNote.noteId)) {
            resetCurrentNote();
            if (noteStore.notes.length > 0) {
                handleNoteSelect(noteStore.notes[0]);
            }
        }
        ElMessage.success('批量删除成功');
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败：' + error.message);
        }
    }
};

// 添加重置当前笔记的方法
const resetCurrentNote = () => {
    // const userId = SignUtil.getUserId();
    Object.assign(currentNote, {
        noteId: 0,
        // userId: userId ? Number(userId) : 0,
        courseId: 0,
        chapterId: 0,
        knowledgeId: 0,
        noteTitle: '新建笔记',
        noteContent: '',
        isPublic: '0',
        createTime: new Date(),
        updateTime: new Date(),
        createBy: '',
        updateBy: '',
        businessFlag: ''
    });
};

// 定义搜索函数
const searchFunction = (input: string): Array<Object> => {
    console.log('笔记搜索：', input);
    noteStore.setSearchQuery(input);
    return noteStore.notes
        .filter(note => 
            note.noteTitle.toLowerCase().includes(input.toLowerCase()) ||
            note.noteContent.toLowerCase().includes(input.toLowerCase())
        )
        .map(note => ({
            title: note.noteTitle,
            path: `/note/notewrite?id=${note.noteId}`
        }));
};

// 定义搜索提示函数
const searchPromptFunction = (input: string): Array<Object> => {
    console.log('笔记搜索提示：', input);
    return noteStore.notes
        .filter(note => note.noteTitle.toLowerCase().includes(input.toLowerCase()))
        .slice(0, 5)
        .map(note => ({
            title: note.noteTitle,
            path: `/note/notewrite?id=${note.noteId}`
        }));
};

// 注入父组件提供的函数
const takeOverSearch = inject<(
    search: (input: string) => Array<Object>,
    prompt: (input: string) => Array<Object>,
    placeholder: string | undefined
) => void>("takeOverSearch");

const releaseSearch = inject<() => void>("releaseSearch");

onMounted(() => {
    // 接管搜索事件
    if (takeOverSearch) {
        takeOverSearch(searchFunction, searchPromptFunction, "搜索笔记");
    }
});

onUnmounted(() => {
    // 释放搜索件
    if (releaseSearch) {
        releaseSearch();
    }
});
</script>

<style scoped>
.noteView {
    width: var(--width);
    height: calc(100vh - 60px);
    display: flex;
    overflow: hidden;
    margin-top: 60px;
    background:  #f5f7fa98;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); 
    margin-top: 10%;
    margin-bottom: 5%;
}

.noteContainer {
    flex: 1;
    display: flex;
    /* background: #f5f7fa98; */
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    height: 100%;
}

.noteList {
    width: 30%;
    border-right: 1px solid #ebeef5;
    display: flex;
    flex-direction: column;
    /* background-color: #fff; */
}

.toolbar {
    width: 100%;
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    /* background-color: #f9f9f9; */
}

.left-tools {
    display: flex;
    gap: 12px;
    align-items: center;
}

.left-tools .el-button {
    background: #f0f7ff;
    border: 1px solid #409EFF;
    color: #409EFF;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.noteContent {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.editor-container {
    flex: 1;
    display: flex;
    position: relative;
    padding: 20px;
    overflow: hidden;
}

.note-editor {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: auto;
}

/* 自定义滚动条样式 */
.note-editor::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.note-editor::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
}

.note-editor::-webkit-scrollbar-track {
    background: transparent;
}

/* 文字换行样式 */
:deep(.el-textarea__inner) {
    white-space: pre-wrap !important;
    word-wrap: break-word !important;
    word-break: break-all !important;
    overflow-wrap: break-word !important;
}

.previewArea {
    white-space: pre-wrap !important;
    word-wrap: break-word !important;
    word-break: break-all !important;
    overflow-wrap: break-word !important;
}

/* 隐藏右侧滚动条 */
::-webkit-scrollbar {
    width: 0;
    height: 0;
}

/* 动画效果 */
.el-button {
    transition: all 0.3s;
}

.el-button:hover {
    transform: translateY(-2px);
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
    .noteList {
        width: 250px;
    }
    
    .toolbar {
        flex-direction: column;
        gap: 10px;
    }
    
    .left-tools, .right-tools {
        width: 100%;
        justify-content: center;
    }
}
</style>

